package com.example.administrator.timereminder;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.content.Intent;
import java.util.Calendar;
import android.app.PendingIntent;
import android.app.AlarmManager;

public class MainActivity extends AppCompatActivity  implements OnClickListener{
    private static MainActivity appRef = null;
    private Button b_call_service, b_exit_service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appRef = this;
        b_call_service = (Button) findViewById(R.id.call_alarm_service);
        b_call_service.setOnClickListener(this);
        b_exit_service = (Button) findViewById(R.id.exit);
        b_exit_service.setOnClickListener(this);
    }

    public static MainActivity getApp() {
        return appRef;
    }

    public void btEvent(String data) {
        setTitle(data);
    }

    public void onClick(View arg0) {
        if (arg0 == b_call_service) {
            setTitle("Waiting... Alarm=5");
            Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);

            /*
              PendingIntent.getBroadcast()通过广播来实现闹钟提示
              PendingIntent可以说是 Intent的进一步封装
              他既包含了Intent的描述又是Intent行为的执行
             */
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

            //设置按钮等待的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 3);

            /*
            第一个参数表示闹钟类型：当系统进入睡眠状态时，这种类型的闹铃也会唤醒系统。
            第二个参数表示闹钟执行时间。
            第三个参数表示闹钟响应动作。

             */
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), p_intent);
        }

        if (arg0 == b_exit_service) {
            Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.cancel(p_intent);
            finish();
        }
    }
}
